#include "taskbyperson.h"
#include "ui_taskbyperson.h"
#include "mainwindow.h"
#include <QChartView>
#include <QPieSeries>
#include <QPieSlice>
#include <QGraphicsLinearLayout>

class CustomLegendItem : public QGraphicsWidget
{
public:
    CustomLegendItem(const QString& label, const QColor& color, QGraphicsItem* parent = nullptr)
        : QGraphicsWidget(parent), m_label(label), m_color(color)
    {
        setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
        setMinimumHeight(20);
    }

    QSizeF sizeHint(Qt::SizeHint hint, const QSizeF& size = QSizeF()) const override
    {
        if (hint == Qt::PreferredSize)
        {
            QFontMetrics fm(font());
            QSizeF textSize = fm.size(Qt::TextSingleLine, m_label);
            return QSizeF(textSize.width() + 30, 20);
        }
        return QGraphicsWidget::sizeHint(hint, size);
    }

protected:
    void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override
    {
        Q_UNUSED(option);
        Q_UNUSED(widget);

        QRectF rect = boundingRect();
        painter->setRenderHint(QPainter::Antialiasing);
        painter->setPen(Qt::NoPen);
        painter->setBrush(m_color);
        painter->drawRect(rect.topLeft().x()+15,rect.topLeft().y()+5,15,15);

        painter->setPen(Qt::black);
        painter->setFont(font());
        painter->drawText(rect.adjusted(45, 0, 0, 0), Qt::AlignVCenter, m_label);
    }

private:
    QString m_label;
    QColor m_color;
};


TaskByPerson::TaskByPerson(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TaskByPerson)
{
    ui->setupUi(this);
    this->setLayout(ui->gridLayout);

    //MainWindow *mw = static_cast<MainWindow *>(parent);
    m_mwindow = static_cast<MainWindow *>(QWidget::parentWidget());
    m_mwindow->initComboBoxData(ui->cb_personName,"研发人员","");
    QDate curdate = QDate::currentDate();

    ui->de_startDate->setMaximumDate(curdate);
    ui->de_startDate->setMinimumDate(curdate.addDays(-180));

    ui->de_endDate->setMinimumDate(curdate.addDays(-180));
    ui->de_endDate->setMaximumDate(curdate);

    QDate sDate=curdate.addDays(-30);
    QDate eDate =curdate;
    ui->de_startDate->setDate(sDate);
    ui->de_endDate->setDate(eDate);
    m_personTaskGnt = new GanttModel() ;

    //设置列表view的表头
    QStringList headlist;
    headlist <<"任务名称"<<"类型"<<"预计开始"<<"截止日期"<<"完成日期"<<"状态"<<"项目名称"<<"历史累计耗时"<<"ID";
    m_personTaskGnt->SetHorHeaderData(headlist);

    QVector<int> headListWidth = {200,40,80,80,80,60,120,80,50}; // 设置列宽
    m_personTaskGnt->SetHeaderWidth(headListWidth);

    m_personTaskGnt->SetStartEndData(sDate,eDate);

    QVBoxLayout *gntlayout = new QVBoxLayout();
    gntlayout->addWidget(m_personTaskGnt);
    gntlayout->setContentsMargins(0,0,0,0);
    ui->wd_taskGnt->setLayout(gntlayout);

    ui->wd_taskPie->setContentsMargins(0,0,0,0);
    QHBoxLayout *wdlayout = new QHBoxLayout();
    wdlayout->addWidget(ui->wd_taskPie,1);
    wdlayout->addWidget(ui->wd_taskGnt,4);
    wdlayout->setContentsMargins(0,0,0,0);
    ui->wd_taskPerson->setLayout(wdlayout);

    connect(m_personTaskGnt->m_pageBar, &QPageBar::pageChanged, this, [&](int idx) {reflashPagingModelView(m_personTaskGnt,idx);});

}

TaskByPerson::~TaskByPerson()
{
    delete ui;
}

void TaskByPerson::reflashPagingModelView(GanttModel *prjGntModel, int curPage)
{
    prjGntModel->m_pageBar->m_currentPage = curPage;
    int modelType = prjGntModel->GetDataModelType();
    //MainWindow *mw = static_cast<MainWindow *>(QWidget::parentWidget());
    QList<GanttTask> gntTask;
   // qDebug()<<"modelType:"<<modelType;
    if(modelType==1)//根据项目名称获取项目任务
        gntTask=m_mwindow->dbMySql->getTaskDataByPrjName_new(prjGntModel->m_pageBar);
    else if(modelType==2)//根据开发人员姓名获取人员任务
        gntTask=m_mwindow->dbMySql->getTaskDataByDevName_new(prjGntModel->m_pageBar);
    else
        qDebug()<<"unknown datamodeltype:"<<modelType;
    prjGntModel->BindModelData(gntTask);
    prjGntModel->SetGanttModel();
}


void TaskByPerson::on_bt_query_clicked()
{
    QString userName = ui->cb_personName->currentText();

    // 获取记录总数
    QDate showStartDate = ui->de_startDate->date();
    QDate showEndDate = ui->de_endDate->date();
    QString startDate = showStartDate.toString("yyyy-MM-dd");
    QString endDate = showEndDate.toString("yyyy-MM-dd");
    //MainWindow *mw = static_cast<MainWindow *>(QWidget::parentWidget());
    m_personTaskGnt->m_pageBar->m_strWhere = QString(" from zt_task zt  left join zt_project zp on zp.id = zt.project  left join zt_user zu on (zu.account = zt.assignedTo or zu.account = zt.finishedBy ) left join zt_story zs on zs.id = zt.story  left join custom_role cr on cr.`key` = zu.`role` where zu.realname ='%1' /*and zp.status = 'doing'*/ and zt.deleted =1 and zt.closedReason !='cancel'  and ((zt.estStarted <= '%2' and zt.deadline >='%3') or (zt.estStarted <='%4' and zt.deadline >='%5') or (zt.estStarted >= '%6' and zt.deadline <='%7'))")
                                                    .arg(userName)
                                                    .arg(startDate)
                                                    .arg(startDate)
                                                    .arg(endDate)
                                                    .arg(endDate)
                                                    .arg(startDate)
                                                    .arg(endDate);
    m_personTaskGnt->m_pageBar->m_strCols = " zp.name,zs.title,zt.id,zt.name,zt.status,zu.realname,cr.value,zt.estStarted,zt.deadline,zt.consumed,zt.finishedDate  ";
    m_mwindow->dbMySql->getPagingInfo(
        m_personTaskGnt->m_pageBar /*,m_pageBar->m_strWhere*/
        /*,m_pageBar->m_pageRecCount*/);

    m_personTaskGnt->m_pageBar->m_strOrd = QString(" order by zp.name asc ");
    m_personTaskGnt->SetStartEndData(showStartDate,showEndDate);
    m_personTaskGnt->SetDataModelType(2);
    reflashPagingModelView(m_personTaskGnt,1);

    QList<PersonHours> hoursList;
    hoursList=m_mwindow->dbMySql->getPersonHours(userName, showStartDate, showEndDate);
    initPersonPie(hoursList);
}
void TaskByPerson::initPersonPie(QList<PersonHours> &hoursList)
{
    QMap<QString, float> sumByGroup;
    float totalHours=0.0,hour=0.0;

    foreach (PersonHours element, hoursList)
    {
            // 根据组名获取当前组的和，若不存在则初始化为0
            if (!sumByGroup.count(element.projectName))
            {
                sumByGroup[element.projectName] = 0;
            }
            // 更新当前组的和
            hour = element.consumed.toFloat();
            sumByGroup[element.projectName] += hour;
            totalHours+=hour;
 //           qDebug() <<"hour:"<<hour<<"totalHours:"<<totalHours;
    }
    // 输出每个组的和

    for (auto itr = sumByGroup.begin(); itr != sumByGroup.end(); ++itr) {
            qDebug() << itr.key() << ": " << itr.value()<<totalHours;
    }
    //删除原来的布局,设置新的布局
    if(ui->wd_taskPie->layout()!=NULL)
            delete ui->wd_taskPie->layout();

    QVBoxLayout *main_layout = new QVBoxLayout();


    QChartView* view = new QChartView();
    main_layout->addWidget(view);
    ui->wd_taskPie->setLayout(main_layout);
    QChart* chart = new QChart();
    chart->setTitle("项目工时统计【"+QString::number(totalHours)+"】");
    chart->legend()->setAlignment(Qt::AlignBottom);//AlignLeft);
    view->setChart(chart);

    QPieSeries* series = new QPieSeries();
    series->setName("项目工时：饼状图");

    chart->addSeries(series);

    QPieSlice* slice;
    QList<QColor> colorList;
    QList<QString> lenendString1,lenendString2;

    colorList.append(QColor(255,99,71));
    colorList.append(QColor(50,205,50));
    colorList.append(QColor(237,145,33));
    colorList.append(QColor(135,206,235));
    colorList.append(QColor(218,112,214));
    int i=0;
    for (auto itr1 = sumByGroup.begin(); itr1 != sumByGroup.end(); ++itr1) {
         //   qDebug() << itr1.key() << ": " << itr1.value();
            slice = new QPieSlice();
            //slice->setLabel(QString::number(itr1.value()));
            QString a = QString::number(itr1.value()/totalHours*100,'f',0);
            slice->setLabel(a+"%");
            slice->setLabelPosition(QPieSlice::LabelInsideHorizontal);
            slice->setLabelVisible(true);
            slice->setValue(itr1.value()/totalHours);
            slice->setColor(colorList.at(i));
            lenendString1.append(itr1.key());
            lenendString2.append(QString::number(itr1.value()));
           // chart->legend()->markers().at(i)->setLabel(itr1.key());
            i++;

            series->append(slice);
    }

    //qDebug()<<"series:"<<series->count();
    int j=0;
//    foreach (QLegendMarker* marker, chart->legend()->markers())
//    {
//            marker->setLabel(lenendString1.at(j)+":"+lenendString2.at(j)+"\n总工时:"+QString::number(totalHours));
//            j++;
//    }
    j=0;
    QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(Qt::Vertical);
    // 添加自定义图例项
    for (QPieSlice* slice1 : series->slices())
    {
            QString label = lenendString1.at(j)+":"+lenendString2.at(j);
            QColor color = slice1->color();
           // qDebug()<<label<<color;
            CustomLegendItem* item = new CustomLegendItem(label, color);
            layout->addItem(item);
            j++;
    }
    chart->legend()->setLayout(layout);
    //series->setVerticalPosition(0.15);
}
